import Vue from 'vue'
import Router from 'vue-router'
import { GetPermission } from "../api/public.js";
import { Error } from "../utils/element.config.js";
import store from "../vuex/store.js";

Vue.use(Router)
let routes = [
  {path: '/', redirect: "/login"},
  {
    path: '/login',
    name: "考试通入口",
    component: () => import("../components/Login.vue")
  },
  {
    path: '/index',
    name: "考试通主页",
    component: () => import("../components/Index.vue"),
    children: []
  },
  {
    path: '/test/:id',
    props: true,
    name: "考试页面",
    component: () => import("../components/TestPage.vue")
  }
]

/** 创建一个路由实例 **/
let router = new Router({
  mode: 'history', // #
  routes
});

/** 存放动态路由组件 **/
const dynamicRouter = {
  'sjgl': {
    path: 'sjgl',
    name: "试卷管理",
    component: () => import("../components/menu/sjgl.vue")
  },
  'tkzx': {
    path: 'tkzx',
    name: "题库中心",
    component: () => import("../components/menu/tkzx.vue")
  },
  'wdks': {
    path: 'wdks',
    name: "我的考试",
    component: () => import("../components/menu/wdks.vue")
  },
  'yygl': {
    path: 'yygl',
    name: "预约管理",
    component: () => import("../components/menu/yygl.vue")
  }
}

/** 配置前置路由守卫 **/
router.beforeEach((to, from, next) => {
  console.log("前置路由执行")
  /* 判断是否带token */
  if( Boolean(sessionStorage.token) ){

    /* 登陆后跳转到登录页, 重定向回主页 */
    if( to.path === '/login' || to.path === '/' ){
      Error("请先退出登录");
      next("/index");
      return;
    }

    /* 判断此时菜单是否已经生成了 */
    if( !store.state.isMenu ){

      /* 发起请求, 获取权限列表 */
      GetPermission().then(result => {
        if( result.code === 200 ){
          let userInfo = result.data.userInfo;
          /* 将数据发送给 vuex 管理 */
          store.commit('setUserInfo', userInfo);
          /* 设置动态菜单栏的路由, 获取到重定向的路由地址 */
          let redirectPath = setRoutes(userInfo.permissions);

          store.commit('setIsMenu');
          /* 重定向路由 */
          if( to.fullPath === '/index' ){
            next(redirectPath);
            /* return防止继续执行, 不知道有什么小情况 */
            // return;
          }else{
            next();
          }
        }
      })
    }

  }else{

    /* 未登录进入主页, 跳转到登录页 */
    if( to.path !== '/login' ){
      Error("请先进行登录");
      next("/login");
      return;
    }

  }

  next();
})

/** 动态菜单栏实现 **/
function setRoutes(permissions){
  let redirectPath = '';
  router.options.routes.forEach(item => {
    /* 拿到主页的item */
    if( item.path === '/index' ){
      /* 修改主页路由的重定向 */
      redirectPath = "/index/" + permissions[0].component;
      /* 遍历把权限列表放到路由下 */
      permissions.forEach(per => {
        if( item.children.length < permissions.length )
          item.children.push(dynamicRouter[per['component']]);
      })
      /* 将菜单数据放到vuex中 */
      store.commit('setMenu', item.children);
    }
    /* 把路由再注册一次 */
    router.addRoute(item);
  })
  return redirectPath;
}

/** 配置后置路由守卫 **/
router.afterEach((to, from) => {
  console.log("后置路由执行")
})

export default router;
